// This code was taken from this site: http://note.sonots.com/EngNote/CompLang/cpp/getopt.html
/*
POSIX getopt for Windows

AT&T Public License

Code given out at the 1985 UNIFORUM conference in Dallas.  
*/
#include "stdafx.h"
#include "getopt.h"
#include <string.h>

namespace PhotonMapping
{

#define NULL	0
#define EOF	(-1)
#define ERR(s, c)	if(opterr){\
	char errbuf[2];\
	errbuf[0] = c; errbuf[1] = _T('\n');\
	_fputts(argv[0], stderr);\
	_fputts(s, stderr);\
	_fputtc(c, stderr);}

int	opterr = 1;
int	optind = 1;
int	optopt;
tchar *optarg;

int getopt(int	argc, tchar	**argv, tchar *opts)
{
	static int sp = 1;
	register int c;
	register tchar *cp;

	if(sp == 1)
		if(optind >= argc ||
			argv[optind][0] != _T('-') || argv[optind][1] == _T('\0'))
			return(EOF);
		else if(_tcscmp(argv[optind], _T("--")) == NULL) {
			optind++;
			return(EOF);
		}
		optopt = c = argv[optind][sp];
		if(c == _T(':') || (cp=_tcschr(opts, c)) == NULL) {
			ERR(_T(": illegal option -- "), c);
			if(argv[optind][++sp] == _T('\0')) {
				optind++;
				sp = 1;
			}
			return _T('?');
		}
		if(*++cp == _T(':')) {
			if(argv[optind][sp+1] != _T('\0'))
				optarg = &argv[optind++][sp+1];
			else if(++optind >= argc) {
				ERR(_T(": option requires an argument -- "), c);
				sp = 1;
				return _T('?');
			} else
				optarg = argv[optind++];
			sp = 1;
		} else {
			if(argv[optind][++sp] == _T('\0')) {
				sp = 1;
				optind++;
			}
			optarg = NULL;
		}
		return(c);
}

} // namespace CacheSim
